using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using THANHTUNGO.Portal.Components.Security;
using THANHTUNGO.Portal.Components.Settings;
using THANHTUNGO.Portal.Components.UI;

namespace THANHTUNGO.Portal.Modules.TAB
{
    public partial class TabEdit : EditItemPage
    {
        protected ArrayList contentList;
        protected ArrayList leftList;
        protected ArrayList rightList;

        protected override void OnInit(EventArgs e)
        {
            if (!PortalSecurity.IsInRole("1"))
            {
                bool isEditable = PortalSecurity.HasEditPermission(this.ModuleID);
                bool isAddable = PortalSecurity.HasAddPermission(this.ModuleID);
                bool isDeleteadble = PortalSecurity.HasDeletePermission(this.ModuleID);
                bool isPropertyable = PortalSecurity.HasPropertyPermission(this.ModuleID);

                btnAddModule.Enabled = isAddable;
                btnDeleteLeftPane.Enabled = btnDeleteRightPane.Enabled = btnDeleteContentPane.Enabled = isDeleteadble;
                btnEditLeftPane.Enabled = btnEditRightPane.Enabled = btnEditContentPane.Enabled = isEditable;

                btnUpLeftPane.Enabled = btnUpRightPane.Enabled = btnUpContentPane.Enabled = isEditable;
                btnDownLeftPane.Enabled = btnDownRightPane.Enabled = btnDownContentPane.Enabled = isEditable;
                btnRightLeftPane.Enabled = btnRightContentPane.Enabled = isEditable;
                btnLeftRightPane.Enabled = btnLeftContentPane.Enabled = isEditable;

                btnSecurityLeftPane.Enabled = btnSecurityRightPane.Enabled = btnSecurityContentPane.Enabled = isPropertyable;

                ButtonCancel = this.btnCancel;
                ButtonUpdate = this.btnUpdate;
            }

            ButtonCancel = this.btnCancel;
            ButtonUpdate = this.btnUpdate;

            base.OnInit(e);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // If first visit to the page, update all entries
            if (!IsPostBack)
            {
                BindData();
            }
        }

        protected void btnAddModule_Click(Object sender, ImageClickEventArgs e)
        {
            // All new modules go to the end of the contentpane
            Module m = new Module();
            m.Title = moduleTitle.Text;
            m.ModuleDefinitionID = Int32.Parse(moduleType.SelectedItem.Value);
            m.Order = 999;

            // save to database
            Configuration config = new Configuration();
            m.ID = config.AddModule(TabID, m.Order, ddlPane.SelectedValue, true, m.Title, m.ModuleDefinitionID, 0, "0;", "1;", "1;", "1;", "1;");

            // Obtain portalId from Current Context
            PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];

            // reload the portalSettings from the database
            HttpContext.Current.Items["PortalSettings"] = new PortalSettings(portalSettings.ID, TabID);

            // reorder the modules in the content pane
            ArrayList modules = GetModules("ContentPane");
            OrderModules(modules);

            // resave the order
            foreach (Module item in modules)
            {
                config.UpdateModuleOrder(item.ID, item.Order, "ContentPane");
            }

            // Redirect to the same page to pick up changes
            Response.Redirect(Request.RawUrl);
        }
       
        protected void SaveTabData()
        {
            // Construct Authorized User Roles string
            string authorizedRoles = "";

            foreach (ListItem item in chkRoles.Items)
            {
                if (item.Selected)
                {
                    authorizedRoles = authorizedRoles + item.Value + ";";
                }
            }

            // Obtain PortalSettings from Current Context
            PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];

            // update Tab info in the database
            Configuration config = new Configuration();
            config.UpdateTab(portalSettings.ID, TabID, tabName.Text, portalSettings.ActiveTab.Order, authorizedRoles, ddlThemeName.SelectedValue, chkLeftPane.Checked, chkRightPane.Checked);
        }
        
        private static bool checkRole(string roleID, string roleString)
        {
            foreach (string r in roleString.Split(';'))
            {
                if (roleID.Trim() == r.Trim())
                {
                    return true;
                }
            }
            return false;
        }


        private void BindData()
        {
            // Obtain PortalSettings from Current Context
            PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];
            Tab tab = portalSettings.ActiveTab;

            // Populate Tab Names, etc.
            tabName.Text = tab.Name;
            ddlThemeName.SelectedValue = tab.ThemeName;
            chkLeftPane.Checked = tab.ShowLeftPane;
            chkRightPane.Checked = tab.ShowRightPane;


            // Populate checkbox list with all security roles for this portal
            // and "check" the ones already configured for this tab
            DataTable roles = Role.SelectAll().Tables[0];

            // Clear existing items in checkboxlist
            chkRoles.Items.Clear();
            /*
            ListItem allItem = new ListItem();
            allItem.Text = "All Users";
            allItem.Value = "0";

            if (checkRole("0", tab.AuthorizedRoles))
            {
                allItem.Selected = true;
            }
            chkRoles.Items.Add(allItem);
            */
            foreach (DataRow row in roles.Rows)
            {
                ListItem item = new ListItem();
                item.Text = (string) row["Name"];
                item.Value = row["ID"].ToString();

                if (checkRole(item.Value, tab.AuthorizedRoles))
                {
                    item.Selected = true;
                }

                chkRoles.Items.Add(item);
            }

            // Populate the "Add Module" Data
            Configuration config = new Configuration();
            moduleType.DataSource = config.GetModuleDefinitions(portalSettings.ID);
            moduleType.DataBind();

            // Populate Right Hand Module Data
            rightList = GetModules("RightPane");
            lstRightPane.DataBind();

            // Populate Content Pane Module Data
            contentList = GetModules("ContentPane");
            lstContentPane.DataBind();

            // Populate Left Hand Pane Module Data
            leftList = GetModules("LeftPane");
            lstLeftPane.DataBind();
        }

        private ArrayList GetModules(string pane)
        {
            // Obtain PortalSettings from Current Context
            PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];
            ArrayList paneModules = new ArrayList();

            foreach (Module module in portalSettings.ActiveTab.Modules)
            {
                if ((module.PaneName).ToLower() == pane.ToLower())
                {
                    Module m = new Module();
                    m.Title = module.Title;
                    m.ID = module.ID;
                    m.ModuleDefinitionID = module.ModuleDefinitionID;
                    m.Order = module.Order;
                    paneModules.Add(m);
                }
            }

            return paneModules;
        }

        protected static void OrderModules(ArrayList list)
        {
            int i = 1;

            // sort the arraylist
            list.Sort();

            // renumber the order
            foreach (Module m in list)
            {
                // number the items 1, 3, 5, etc. to provide an empty order
                // number when moving items up and down in the list.
                m.Order = i;
                i += 2;
            }
        }

        protected void btnEditLeftPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstLeftPane.SelectedIndex != -1)
            {
                int mid = Int32.Parse(lstLeftPane.SelectedItem.Value);
                Response.Redirect("~/Modules/MODULE/ModuleSetting.aspx?tabid=" + TabID + "&mid=" + mid + "&returnUrl=" + Server.UrlEncode(Request.RawUrl));
            }
        }

        protected void btnEditContentPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstContentPane.SelectedIndex != -1)
            {
                int mid = Int32.Parse(lstContentPane.SelectedItem.Value);
                Response.Redirect("~/Modules/MODULE/ModuleSetting.aspx?tabid=" + TabID + "&mid=" + mid + "&returnUrl=" + Server.UrlEncode(Request.RawUrl));
            }
        }

        protected void btnDeleteLeftPane_Click(object sender, ImageClickEventArgs e)
        {
            ArrayList modules = GetModules("LeftPane");

            if (lstLeftPane.SelectedIndex != -1)
            {
                Module m = (Module) modules[lstLeftPane.SelectedIndex];
                if (m.ID > -1)
                {
                    // must delete from database too
                    Configuration config = new Configuration();
                    config.DeleteModule(m.ID);
                }
            }
            // Redirect to the same page to pick up changes.
            Response.Redirect(Request.RawUrl);
        }

        protected void btnDeleteContentPane_Click(object sender, ImageClickEventArgs e)
        {
            ArrayList modules = GetModules("ContentPane");

            if (lstContentPane.SelectedIndex != -1)
            {
                Module m = (Module) modules[lstContentPane.SelectedIndex];
                if (m.ID > -1)
                {
                    Configuration config = new Configuration();
                    config.DeleteModule(m.ID);
                }
            }
            // Redirect to the same page to pick up changes.
            Response.Redirect(Request.RawUrl);
        }

        protected void btnDeleteRightPane_Click(object sender, ImageClickEventArgs e)
        {
            ArrayList modules = GetModules("RightPane");

            if (lstRightPane.SelectedIndex != -1)
            {
                Module m = (Module) modules[lstRightPane.SelectedIndex];
                if (m.ID > -1)
                {
                    Configuration config = new Configuration();
                    config.DeleteModule(m.ID);
                }
            }
            // Redirect to the same page to pick up changes.
            Response.Redirect(Request.RawUrl);
        }

        protected void btnEditRightPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstRightPane.SelectedIndex != -1)
            {
                int mid = Int32.Parse(lstRightPane.SelectedItem.Value);
                Response.Redirect("~/Modules/MODULE/ModuleSetting.aspx?tabid=" + TabID + "&mid=" + mid + "&returnUrl=" + Server.UrlEncode(Request.RawUrl));
            }
        }

        protected void btnUpDownLeftPane_Click(object sender, ImageClickEventArgs e)
        {
            string commandName = ((ImageButton) sender).CommandName;
            ArrayList modules = GetModules("LeftPane");

            if (lstLeftPane.SelectedIndex != -1)
            {
                int delta;

                // Determine the delta to apply in the order number for the module.
                // within the list.  +3 moves down one item; -3 moves up one item.

                if (commandName == "down")
                {
                    delta = 3;
                }
                else
                {
                    delta = -3;
                }

                Module m;
                m = (Module) modules[lstLeftPane.SelectedIndex];
                m.Order += delta;

                // reorder the modules in the content pane.
                OrderModules(modules);

                // resave the order.
                Configuration config = new Configuration();
                foreach (Module item in modules)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "LeftPane");
                }
            }

            // Redirect to the same page to pick up changes
            Response.Redirect(Request.RawUrl);
        }

        protected void btnUpDownContentPane_Click(object sender, ImageClickEventArgs e)
        {
            string commandName = ((ImageButton) sender).CommandName;
            ArrayList modules = GetModules("ContentPane");

            if (lstContentPane.SelectedIndex != -1)
            {
                int delta;

                // Determine the delta to apply in the order number for the module.
                // within the list.  +3 moves down one item; -3 moves up one item.

                if (commandName == "down")
                {
                    delta = 3;
                }
                else
                {
                    delta = -3;
                }

                Module m;
                m = (Module) modules[lstContentPane.SelectedIndex];
                m.Order += delta;

                // reorder the modules in the content pane.
                OrderModules(modules);

                // resave the order.
                Configuration config = new Configuration();
                foreach (Module item in modules)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "ContentPane");
                }
            }

            // Redirect to the same page to pick up changes
            Response.Redirect(Request.RawUrl);
        }

        protected void btnUpDownRightPane_Click(object sender, ImageClickEventArgs e)
        {
            string commandName = ((ImageButton) sender).CommandName;
            ArrayList modules = GetModules("RightPane");

            if (lstRightPane.SelectedIndex != -1)
            {
                int delta;

                // Determine the delta to apply in the order number for the module.
                // within the list.  +3 moves down one item; -3 moves up one item.

                if (commandName == "down")
                {
                    delta = 3;
                }
                else
                {
                    delta = -3;
                }

                Module m;
                m = (Module) modules[lstRightPane.SelectedIndex];
                m.Order += delta;

                // reorder the modules in the content pane.
                OrderModules(modules);

                // resave the order.
                Configuration config = new Configuration();
                foreach (Module item in modules)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "RightPane");
                }
            }

            // Redirect to the same page to pick up changes
            Response.Redirect(Request.RawUrl);
        }

        protected void btnRightLeftPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstLeftPane.SelectedIndex != -1)
            {
                // get source arraylist
                ArrayList sourceList = GetModules("LeftPane");

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                Module m = (Module) sourceList[lstLeftPane.SelectedIndex];

                // add it to the database
                Configuration config = new Configuration();
                config.UpdateModuleOrder(m.ID, 998, "ContentPane");

                // delete it from the source list
                sourceList.RemoveAt(lstLeftPane.SelectedIndex);

                // Obtain portalId from Current Context
                PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];

                // reload the portalSettings from the database
                HttpContext.Current.Items["PortalSettings"] = new PortalSettings(portalSettings.ID, TabID);

                // reorder the modules in the source pane
                sourceList = GetModules("LeftPane");
                OrderModules(sourceList);

                // resave the order
                foreach (Module item in sourceList)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "LeftPane");
                }

                // reorder the modules in the target pane
                ArrayList targetList = GetModules("ContentPane");
                OrderModules(targetList);

                // resave the order
                foreach (Module item in targetList)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "ContentPane");
                }

                // Redirect to the same page to pick up changes
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void btnLeftRightPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstRightPane.SelectedIndex != -1)
            {
                // get source arraylist
                ArrayList sourceList = GetModules("RightPane");

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                Module m = (Module) sourceList[lstRightPane.SelectedIndex];

                // add it to the database
                Configuration config = new Configuration();
                config.UpdateModuleOrder(m.ID, 998, "ContentPane");

                // delete it from the source list
                sourceList.RemoveAt(lstRightPane.SelectedIndex);

                // Obtain portalId from Current Context
                PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];

                // reload the portalSettings from the database
                HttpContext.Current.Items["PortalSettings"] = new PortalSettings(portalSettings.ID, TabID);

                // reorder the modules in the source pane
                sourceList = GetModules("RightPane");
                OrderModules(sourceList);

                // resave the order
                foreach (Module item in sourceList)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "RightPane");
                }

                // reorder the modules in the target pane
                ArrayList targetList = GetModules("ContentPane");
                OrderModules(targetList);

                // resave the order
                foreach (Module item in targetList)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "ContentPane");
                }

                // Redirect to the same page to pick up changes
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void btnLeftContentPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstContentPane.SelectedIndex != -1)
            {
                // get source arraylist
                ArrayList sourceList = GetModules("ContentPane");

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                Module m = (Module) sourceList[lstContentPane.SelectedIndex];

                // add it to the database
                Configuration config = new Configuration();
                config.UpdateModuleOrder(m.ID, 998, "LeftPane");

                // delete it from the source list
                sourceList.RemoveAt(lstContentPane.SelectedIndex);

                // Obtain portalId from Current Context
                PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];

                // reload the portalSettings from the database
                HttpContext.Current.Items["PortalSettings"] = new PortalSettings(portalSettings.ID, TabID);

                // reorder the modules in the source pane
                sourceList = GetModules("ContentPane");
                OrderModules(sourceList);

                // resave the order
                foreach (Module item in sourceList)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "ContentPane");
                }

                // reorder the modules in the target pane
                ArrayList targetList = GetModules("LeftPane");
                OrderModules(targetList);

                // resave the order
                foreach (Module item in targetList)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "LeftPane");
                }

                // Redirect to the same page to pick up changes
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void btnRightContentPane_Click(object sender, ImageClickEventArgs e)
        {
            if (lstContentPane.SelectedIndex != -1)
            {
                // get source arraylist
                ArrayList sourceList = GetModules("ContentPane");

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                Module m = (Module) sourceList[lstContentPane.SelectedIndex];

                // add it to the database
                Configuration config = new Configuration();
                config.UpdateModuleOrder(m.ID, 998, "RightPane");

                // delete it from the source list
                sourceList.RemoveAt(lstContentPane.SelectedIndex);

                // Obtain portalId from Current Context
                PortalSettings portalSettings = (PortalSettings) Context.Items["PortalSettings"];

                // reload the portalSettings from the database
                HttpContext.Current.Items["PortalSettings"] = new PortalSettings(portalSettings.ID, TabID);

                // reorder the modules in the source pane
                sourceList = GetModules("ContentPane");
                OrderModules(sourceList);

                // resave the order
                foreach (Module item in sourceList)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "ContentPane");
                }

                // reorder the modules in the target pane
                ArrayList targetList = GetModules("RightPane");
                OrderModules(targetList);

                // resave the order
                foreach (Module item in targetList)
                {
                    config.UpdateModuleOrder(item.ID, item.Order, "RightPane");
                }

                // Redirect to the same page to pick up changes
                Response.Redirect(Request.RawUrl);
            }
        }

        protected void btnSecurity_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton btn = (ImageButton) sender;
            if (btn.CommandArgument == "LeftPane")
            {
                if (lstLeftPane.SelectedIndex != -1)
                {
                    // get source arraylist
                    ArrayList sourceList = GetModules(btn.CommandArgument);

                    // get a reference to the module to move
                    // and assign a high order number to send it to the end of the target list
                    Module m = (Module) sourceList[lstLeftPane.SelectedIndex];
                    Response.Redirect("~/Modules/MODULE/ModuleSecurity.aspx?tabid=" + this.TabID + "&mid=" + m.ID + "&returnUrl=" + Server.UrlEncode(Request.RawUrl));
                }
            }
            else if (btn.CommandArgument == "RightPane")
            {
                if (lstRightPane.SelectedIndex != -1)
                {
                    // get source arraylist
                    ArrayList sourceList = GetModules(btn.CommandArgument);

                    // get a reference to the module to move
                    // and assign a high order number to send it to the end of the target list
                    Module m = (Module) sourceList[lstRightPane.SelectedIndex];
                    Response.Redirect("~/Modules/MODULE/ModuleSecurity.aspx?tabid=" + this.TabID + "&mid=" + m.ID + "&returnUrl=" + Server.UrlEncode(Request.RawUrl));
                }
            }
            else
            {
                if (lstContentPane.SelectedIndex != -1)
                {
                    // get source arraylist
                    ArrayList sourceList = GetModules(btn.CommandArgument);

                    // get a reference to the module to move
                    // and assign a high order number to send it to the end of the target list
                    Module m = (Module) sourceList[lstContentPane.SelectedIndex];
                    Response.Redirect("~/Modules/MODULE/ModuleSecurity.aspx?tabid=" + this.TabID + "&mid=" + m.ID + "&returnUrl=" + Server.UrlEncode(Request.RawUrl));
                }
            }
        }

        protected override void OnUpdate(EventArgs e)
        {
            base.OnUpdate(e);
            SaveTabData();
            ReturnToReferrerPage();
        }
    }
}